﻿using System.Data;
using System.Data.SqlClient;

namespace Adams.Public.DataAccess
{
    public static class Announcements
    {
        public static Adams.Public.DataTransfer.Announcements.GetAnnouncements GetAnnouncements()
        {
            var data = new Adams.Public.DataTransfer.Announcements.GetAnnouncements();

            using (SqlDataReader dr = DB.RunDataReader(@"
SELECT COUNT(*) AS TotalRecords 
FROM Announcements.Announcements A
WHERE DATEDIFF(d, GetDate(), A.EndDate) > 0 OR DATEDIFF(d, GetDate(), A.StartDate) > 0

SELECT A.*
FROM Announcements.Announcements A
WHERE DATEDIFF(d, GetDate(), A.EndDate) > 0 OR DATEDIFF(d, GetDate(), A.StartDate) > 0
", CommandType.Text))
            {
                dr.Read();
                data.Count = dr["TotalRecords"].DbInt();

                dr.NextResult();
                data.Announcements = new Shared.Entities.Announcements.AnnouncementCollection();
                while (dr.Read())
                {
                    var announcement = new Shared.Entities.Announcements.Announcement();
                    announcement.ID = dr["AnnouncementID"].DbInt();
                    announcement.Title = dr["Title"].DbString();
                    announcement.ShortDescription = dr["ShortDescription"].DbString();
                    announcement.StartDate = dr["StartDate"].DbDate();
                    announcement.EndDate = dr["EndDate"].DbDate();
                    announcement.Link = dr["Link"].DbString();
                    data.Announcements.Add(announcement);
                }
            }

            return data;
        }

        public static Adams.Public.DataTransfer.Announcements.GetAnnouncement GetAnnouncement(int id)
        {
            var data = new Adams.Public.DataTransfer.Announcements.GetAnnouncement();

            using (SqlDataReader dr = DB.RunDataReader(@"
SELECT A.*
FROM Announcements.Announcements A
WHERE A.AnnouncementID = @AnnouncementID
", CommandType.Text,
    DB.CreateParameter("@AnnouncementID", id)))
            {
                var announcement = new Shared.Entities.Announcements.Announcement();

                if (dr.HasRows)
                {
                    dr.Read();
                    announcement.ID = dr["AnnouncementID"].DbInt();
                    announcement.Title = dr["Title"].DbString();
                    announcement.ShortDescription = dr["ShortDescription"].DbString();
                    announcement.LongDescription = dr["LongDescription"].DbString();
                    announcement.StartDate = dr["StartDate"].DbDate();
                    announcement.EndDate = dr["EndDate"].DbDate();
                    announcement.Link = dr["Link"].DbString();
                }

                data.Announcement = announcement;

                return data;
            }
        }
    }
}
